package com.hsogoo.study.leetcode.reverselist;

/**
 * 反转链表
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 * 限制：0 <= 节点个数 <= 5000
 * @Author huangsaigang
 * Created @2020-04-16.
 */
public class Solution {

    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static ListNode reverseList(ListNode head) {
        ListNode reverse = new ListNode(-1);
        ListNode next = null;
        while(head.next != null){
            //保存当前节点的后续节点
            next = head.next;
            //把当前节点放在反转节点的最前面
            head.next = reverse.next;
            reverse.next = head;
            //遍历后续节点
            head = next;
        }
        //把当前节点放在反转节点的最前面，并去除虚拟节点
        head.next = reverse.next;
        return head;
    }

    public static void main(String[] args) {
        ListNode o1 = new ListNode(1);
        ListNode o2 = new ListNode(2);
        ListNode o3 = new ListNode(3);
        ListNode o4 = new ListNode(4);
        ListNode o5 = new ListNode(5);
        o1.next = o2;
        o2.next = o3;
        o3.next = o4;
        o4.next = o5;
        printNode(o1);
        ListNode r = reverseList(o1);
        printNode(r);
    }

    private static void printNode(ListNode node){
        StringBuilder sb = new StringBuilder();
        sb.append(node.val);
        while(node.next != null){
            sb.append("-->").append(node.next.val);
            node = node.next;
        }
        System.out.println(sb.toString());
    }
}
